<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="配置" prop="configId">
        <el-select
          v-model="queryParams.configId"
          placeholder="请选择配置"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="config in configList"
            :key="config.id"
            :label="config.name"
            :value="config.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="错误码" prop="errorCode">
        <el-input
          v-model="queryParams.errorCode"
          placeholder="请输入错误码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="编号" align="center" prop="id" width="80" />
      <el-table-column label="配置" align="center" prop="configId" width="100">
        <template #default="scope">
          {{ getConfigName(scope.row.configId) }}
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="imageUrl" width="120">
        <template #default="scope">
          <el-image
            v-if="scope.row.imageUrl"
            :src="scope.row.imageUrl"
            :preview-src-list="[scope.row.imageUrl]"
            fit="cover"
            style="width: 60px; height: 60px"
            preview-teleported
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="人脸数量" align="center" prop="faceCount" width="100" />
      <el-table-column label="识别结果" align="center" width="120">
        <template #default="scope">
          <el-tag v-if="!scope.row.errorCode" type="success">成功</el-tag>
          <el-tag v-else type="danger">失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="错误码" align="center" prop="errorCode" width="100" />
      <el-table-column label="错误信息" align="center" prop="errorMsg" :show-overflow-tooltip="true" />
      <el-table-column label="耗时(ms)" align="center" prop="duration" width="100" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row)"
          >
            详情
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['ai:face-record:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 详情弹窗 -->
  <el-dialog v-model="detailVisible" title="识别详情" width="800px">
    <div v-if="detailData">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="记录编号">{{ detailData.id }}</el-descriptions-item>
        <el-descriptions-item label="配置名称">{{ getConfigName(detailData.configId) }}</el-descriptions-item>
        <el-descriptions-item label="人脸数量">{{ detailData.faceCount }}</el-descriptions-item>
        <el-descriptions-item label="识别耗时">{{ detailData.duration }}ms</el-descriptions-item>
        <el-descriptions-item label="错误码">{{ detailData.errorCode || '-' }}</el-descriptions-item>
        <el-descriptions-item label="错误信息">{{ detailData.errorMsg || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ formatDate(detailData.createTime) }}
        </el-descriptions-item>
      </el-descriptions>
      
      <!-- 图片预览 -->
      <div class="mt-4" v-if="detailData.imageUrl">
        <h4>原始图片</h4>
        <el-image
          :src="detailData.imageUrl"
          :preview-src-list="[detailData.imageUrl]"
          style="max-width: 100%; max-height: 300px"
          fit="contain"
          preview-teleported
        />
      </div>
      
      <!-- 人脸详情 -->
      <div class="mt-4" v-if="faceDetails && faceDetails.length > 0">
        <h4>人脸详情</h4>
        <el-table :data="faceDetails" border>
          <el-table-column label="序号" type="index" width="60" />
          <el-table-column label="位置 (x, y)" width="120">
            <template #default="scope">
              {{ scope.row.x }}, {{ scope.row.y }}
            </template>
          </el-table-column>
          <el-table-column label="尺寸 (宽×高)" width="120">
            <template #default="scope">
              {{ scope.row.width }}×{{ scope.row.height }}
            </template>
          </el-table-column>
          <el-table-column label="置信度" width="100">
            <template #default="scope">
              {{ (scope.row.confidence * 100).toFixed(2) }}%
            </template>
          </el-table-column>
          <el-table-column label="年龄" width="80">
            <template #default="scope">
              {{ scope.row.age || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="性别" width="80">
            <template #default="scope">
              {{ scope.row.gender || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="情绪" width="100">
            <template #default="scope">
              {{ scope.row.emotion || '-' }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { dateFormatter, formatDate } from '@/utils/formatTime'
import { getFaceRecordPage, deleteFaceRecord, getFaceRecord } from '@/api/ai/face'
import { getFaceConfigPage } from '@/api/ai/face'

/** 人脸记录 列表 */
defineOptions({ name: 'AiFaceRecord' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const configList = ref([]) // 配置列表
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  configId: undefined,
  errorCode: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单

// 详情弹窗
const detailVisible = ref(false)
const detailData = ref(null)
const faceDetails = ref([])

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getFaceRecordPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 获取配置列表 */
const getConfigList = async () => {
  try {
    const data = await getFaceConfigPage({ pageNo: 1, pageSize: 100 })
    configList.value = data.list
  } catch (error) {
    console.error('获取配置列表失败:', error)
  }
}

/** 获取配置名称 */
const getConfigName = (configId: number) => {
  const config = configList.value.find(item => item.id === configId)
  return config ? config.name : `配置${configId}`
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 打开详情 */
const openDetail = async (row) => {
  try {
    // 如果列表数据中已经有faces字段，直接使用，避免重复查询
    if (row.faces !== undefined) {
      detailData.value = { ...row }
      // 解析人脸详情
      if (row.faces) {
        try {
          faceDetails.value = JSON.parse(row.faces)
        } catch (e) {
          faceDetails.value = []
        }
      } else {
        faceDetails.value = []
      }
      detailVisible.value = true
    } else {
      // 如果列表数据不完整，才查询详情接口
      detailData.value = await getFaceRecord(row.id)
      // 解析人脸详情
      if (detailData.value.faces) {
        try {
          faceDetails.value = JSON.parse(detailData.value.faces)
        } catch (e) {
          faceDetails.value = []
        }
      } else {
        faceDetails.value = []
      }
      detailVisible.value = true
    }
  } catch (error) {
    message.error('获取详情失败')
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteFaceRecord(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(() => {
  getConfigList()
  getList()
})
</script>